﻿using System;
using SaleManagement.Domains;
using SaleManagement.Web.App_Code;
using SaleManagement.Services;
using Library.Encryption;

namespace SaleManagement.Web.Pages
{
  public partial class ChangeUserInfo : BasePage
  {
    protected void Page_Load(object sender, EventArgs e)
    {
      if (!IsPostBack && !IsCallback)
      {
        if (CurrentUser != null)
        {
          txtUsername.Enabled = false;
          txtUsername.Text = CurrentUser.Username;
          txtFullname.Text = CurrentUser.FullName;
          txtEmail.Text = CurrentUser.Email;
          txtPhone.Text = CurrentUser.Phone;
          txtAddress.Text = CurrentUser.Address;
        }
        else
        {
          Response.Redirect("../Login.aspx");
        }
      }
    }

    protected void cbxUserInfo_Callback(object source, DevExpress.Web.ASPxCallback.CallbackEventArgs e)
    {
      string para = e.Parameter;
      if(para == "SaveInfo")
      {
        e.Result = SaveInfo();
      }
      else if(para == "ChangePass")
      {
        e.Result = ChangePassword();
      }
    }

    private string SaveInfo()
    {
      try
      {
        UserService userService = new UserService();
        User user = CurrentUser;
        user.FullName = Utilities.SafeString(txtFullname.Text);
        user.Email = Utilities.SafeString(txtEmail.Text);
        user.Phone = Utilities.SafeString(txtPhone.Text);
        user.Address = Utilities.SafeString(txtAddress.Text);
        userService.Save(user);
        CurrentUser = user;
        return string.Empty;
      }
      catch (Exception ex)
      {
        WriteLog(" Save Current User Info", ex);
        return "Có lỗi trong quá trình lưu dữ liệu";
      }
    }

    private string ChangePassword()
    {
      try
      {
        if (txtNewPassword.Text.Trim() != txtRetypeNewPass.Text.Trim() )
        {
          return "Mật khẩu và mật khẩu nhập lại không trùng";
        }
        Domains.User user = CurrentUser;
        user.Password = MD5.Encrypt(txtNewPassword.Text.Trim());
        new UserService().Save(user);
        return string.Empty;
      }
      catch (Exception ex)
      {
        WriteLog("Change Current User Password", ex);
        return "Có lỗi trong quá trình lưu dữ liệu";
      }
    }
  }
}
